import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:life_milestones/MS-Model/MS-milestone.dart';
import 'package:life_milestones/controller/MS-global-user-controller.dart';
import 'package:life_milestones/controller/MS-mile-stone-controller.dart';
import 'package:stroke_text/stroke_text.dart';
import 'package:record/record.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import '../util/MS-audio-player-util.dart';
import '../util/MS-toast-util.dart';
import 'package:provider/provider.dart';
import 'package:svgaplayer_flutter/svgaplayer_flutter.dart';
import 'package:audioplayers/audioplayers.dart';
class MSPostVoicePage extends StatefulWidget {
  final int month;
  const MSPostVoicePage({super.key, required this.month});

  @override
  State<StatefulWidget> createState() {
    return _MSPostVoicePageState();
  }
}

class _MSPostVoicePageState extends State<MSPostVoicePage> {
  final record = AudioRecorder();
  bool isRecording = false;
  bool isOut = false;
  String? currentPath = null;
  MSVoice? path = null;
  int? startTime;
  int? endTime;
  GlobalKey key = GlobalKey();
  startRecord() async {
    var status = await Permission.microphone.status;
    if (status.isDenied) {
      var result = await Permission.microphone.request();
      if (result.isDenied || result.isPermanentlyDenied) {
        showToast(
            "\"LifeMilestones\" requires access to your microphone to record a personal voice.");
        return;
      }
      return;
    }
    setState(() {
      isRecording = true;
      isOut = false;
    });
    var dir = await getApplicationDocumentsDirectory();
    currentPath = '${dir.path}/${DateTime.now().millisecondsSinceEpoch}.m4a';
    await record.start(const RecordConfig(), path: currentPath!);
    startTime = DateTime.now().millisecondsSinceEpoch;
  }

  stopRecord() async {
    if (isRecording && !isOut) {
      final target = await record.stop();
      endTime = DateTime.now().millisecondsSinceEpoch;
      setState(() {
        path = MSVoice(
            length: ((endTime! - startTime!) / 1000).floor(), path: target!);
        isRecording = false;
      });
      endTime = null;
      startTime = null;
    }else{
      setState(() {
        isRecording = false;
        endTime = null;
        startTime = null;
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    loadAnimation();
    super.initState();
  }

  loadAnimation()async{
   await SVGAParser.shared.decodeFromAssets(
        "images/post-voice-record.svga");
    await SVGAParser.shared.decodeFromAssets(
        "images/btn-recording.svga");
  }

  @override
  void dispose() {
    record.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MSMileStoneController>(builder:
        (BuildContext context, MSMileStoneController controller, Widget? c) {
      return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: const Color(0xFF148857),
        body: SizedBox.expand(
            child: Stack(
          children: [
            Positioned(
              left: 0,
              right: 0,
              top: ScreenUtil().statusBarHeight,
              bottom: 0,
              child: Image.asset(
                "images/post-voice-bg.png",
                fit: BoxFit.fitWidth,
              ),
            ),
            Positioned(
                left: 0,
                right: 0,
                top: ScreenUtil().statusBarHeight,
                bottom: 0,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(top: 32.w, left: 24.w),
                      child: InkWell(
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                        child: Image.asset(
                          "images/back.png",
                          width: 25.w,
                          fit: BoxFit.fitWidth,
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 12.w),
                      child: SizedBox(
                        width: double.infinity,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            StrokeText(
                              text: "Things I want to record",
                              strokeWidth: 2.w,
                              strokeColor: const Color(0xFF065F39),
                              textStyle: TextStyle(
                                  fontSize: 25.sp,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white),
                            )
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: EdgeInsets.only(
                            top: 204.w, left: 40.w, right: 40.w),
                        child: SizedBox.expand(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Expanded(
                                  child: Column(
                                children: [
                                  if (path != null)
                                    MSPlayingView(key:ValueKey(path!.path), item: path!,onDelete: ()=>{
                                      setState((){
                                        path = null;
                                      })
                                    },)
                                ],
                              )),
                              Padding(
                                  padding:
                                      EdgeInsets.only(top: 10.w, bottom: 277.w),
                                  child: InkWell(
                                    onTap: () {
                                      if (path != null) {
                                        controller.addMileStone(MSMileStone(
                                            type: Type.voice,
                                            userId: MSGlobalUserController()
                                                .user!
                                                .userId!,
                                            month: widget.month,
                                            content:
                                                jsonEncode(path!.toJson())));
                                        Navigator.of(context).pop();
                                      }
                                    },
                                    child: Container(
                                      width: 165.w,
                                      height: 39.w,
                                      decoration: const BoxDecoration(
                                          image: DecorationImage(
                                              image: AssetImage(
                                                  "images/home-save-button-bg.png"),
                                              fit: BoxFit.fill)),
                                      alignment: Alignment.center,
                                      child: StrokeText(
                                        text: "publish",
                                        strokeColor: Colors.white,
                                        strokeWidth: 1.w,
                                        textStyle: TextStyle(
                                            fontSize: 12.sp,
                                            fontWeight: FontWeight.bold,
                                            color: const Color(0xFF333333)),
                                      ),
                                    ),
                                  )),
                            ],
                          ),
                        ),
                      ),
                    )
                  ],
                )),
            isRecording
                ? Positioned.fill(
                    child: Container(
                    decoration: const BoxDecoration(color: Color(0x99000000)),
                  ))
                : const SizedBox(),
            Positioned(
                bottom: 181.w,
                left: 88.w,
                child:  !isRecording
                    ?Image.asset(
                  "images/post-voice-record-normal.png",
                  width: 200.w,
                  fit: BoxFit.fitWidth,
                ): SizedBox(width: 200.w,child: SVGASimpleImage(assetsName: "images/post-voice-record.svga",),)),
            Positioned(
                bottom: 0.w,
                left: 120.w,
                child: SizedBox(
                  width: 130.w,
                  height: 130.w,
                  child:Stack(
                    children: [
                      if(!isRecording || (isRecording && isOut)) Align(alignment: Alignment.center,child:
                      Image.asset("images/post-voice-record-button-normal.png",
                        width: 80.w,
                        fit: BoxFit.fitWidth,
                      )),
                      if(isRecording && !isOut)Align(alignment: Alignment.center,child:  SizedBox(width: 130.w,height: 130.w, child: SVGASimpleImage(assetsName: "images/btn-recording.svga",),),),
                      Align(alignment: Alignment.center,child: GestureDetector(
                          key:key,
                        onPanDown: (DragDownDetails details){
                          startRecord();
                        },
                        onPanUpdate: (DragUpdateDetails details){
                          RenderBox? renderBox = key.currentContext?.findRenderObject() as RenderBox?;
                          if(renderBox != null){
                            Size size = renderBox.size;
                           Offset position = renderBox.localToGlobal(Offset.zero);
                           if( details.globalPosition.dx > position.dx
                               && details.globalPosition.dx < position.dx + size.width
                           && details.globalPosition.dy > position.dy
                           && details.globalPosition.dy < position.dy + size.height
                           ){
                             setState(() {
                               isOut = false;
                             });
                           }else{
                             setState(() {
                               isOut = true;
                             });
                           }
                          }
                        },
                        onPanEnd: (DragEndDetails details){
                          stopRecord();
                        },
                          ),
                      ),

                    ],
                  ) ,
                ))
          ],
        )),
      );
    });
  }
}


class MSPlayingView extends StatefulWidget{
  final MSVoice item;
  final Function onDelete;
  const MSPlayingView({super.key, required this.item,required this.onDelete});
  @override
  State<StatefulWidget> createState() {
    return _MSPlayingViewState();
  }

}

class _MSPlayingViewState extends State<MSPlayingView> with SingleTickerProviderStateMixin{
  late SVGAAnimationController animationController;
  bool isPlaying = false;
  @override
  void initState() {
    animationController = SVGAAnimationController(vsync: this);
    MSAudioPlayerUtil().addListener(key: widget.item.path, callBack: listener);
    loadAnimation();
    super.initState();
  }

  listener(PlayerState state){
    if(state == PlayerState.playing){
      setState(() {
        isPlaying = true;
      });
    }else{
      setState(() {
        isPlaying = false;
      });
    }
  }

  @override
  void dispose() {
    MSAudioPlayerUtil().removeListener(widget.item.path, listener);
    animationController.dispose();
    MSAudioPlayerUtil().stop();
    super.dispose();
  }
  void loadAnimation() async {
    final videoItem = await SVGAParser.shared.decodeFromAssets(
        "images/playing.svga");
    animationController.videoItem = videoItem;
    animationController.reset();
  }
  @override
  Widget build(BuildContext context) {
    return  InkWell(
      onTap: () async {
        if(!isPlaying){
          await MSAudioPlayerUtil()
              .play(widget.item.path);
        }else{
          await MSAudioPlayerUtil().stop();
        }

      },
      child: Row(
        mainAxisAlignment:
        MainAxisAlignment.spaceBetween,
        children: [
          Container(
            width: 196.w,
            height: 40.w,
            decoration: BoxDecoration(
                color: const Color(0xFF70C37A),
                borderRadius:
                BorderRadius.circular(
                    20.w)),
            padding: EdgeInsets.symmetric(
                horizontal: 20.w),
            child: Row(
              children: [
                if(isPlaying) SizedBox(width: 40.w, height: 40.w, child: const SVGASimpleImage(assetsName:"images/playing.svga",),),
                if(!isPlaying) Container(width: 40.w, height: 40.w,alignment: Alignment.center, child: UnconstrainedBox(
                  child: Image.asset("images/mile-stone-voice.png",width: 28.w,fit: BoxFit.fitWidth,),
                ),),
                Padding(
                  padding: EdgeInsets.only(
                      left: 8.w),
                  child: Text(
                    "${widget.item!.length}S",
                    style: TextStyle(
                        fontSize: 24.sp,
                        color: const Color(
                            0xFF333333)),
                  ),
                )
              ],
            ),
          ),
          InkWell(
            onTap: () {
              widget.onDelete();
            },
            child: Image.asset(
              "images/post-voice-delete.png",
              width: 40.w,
              fit: BoxFit.fitWidth,
            ),
          )
        ],
      ),
    );
  }

}
